import styled from 'styled-components'
import Recaptcha from '../../google/recaptcha'
import { useCallback, useEffect, useState } from 'react'
import WebApp from '@twa-dev/sdk'
import { fetchToken, saveToken } from '../../utils/user'
import Loading from '../../component/Loading'

const Container = styled.div`
    background-color: ${(prop) => prop.theme.background.normal};
    position: fixed;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    left: 0;
    top: 0;
`
interface Prop {
    initData?: string
}

const RecaptchaComponent: React.FC<Prop> = () => {
    const [spinning, setSpinning] = useState(false);
    const check = useCallback(async () => {
        setSpinning(true)
        const recaptcha = await new Recaptcha().init();
        if (!recaptcha) {
            setSpinning(false)
            return;
        }

        const token = fetchToken();
        if (!token && WebApp.initData) {
            saveToken(WebApp.initData)
        }

        // check robot
        recaptcha?.render((success, reset) => {
            if (!success) {
                reset();
                return;
            }
        })
    }, [])

    useEffect(() => {
        check();
    }, [check])

    return <Container id={Recaptcha.robotContainerId}>
        <Loading
            show={spinning}
        />
    </Container>
}

export default RecaptchaComponent